package com.nuo.common.web.interceptor;

import cn.hutool.core.util.StrUtil;
import com.nuo.common.core.constant.TraceLogConstants;
import com.nuo.common.web.util.TraceIdUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 日志追踪拦截器
 *
 * @author LGC
 */
@Slf4j
public class LogTraceInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String traceId = request.getHeader(TraceLogConstants.TRACE_ID_HEADER);
        if (StrUtil.isBlank(traceId)) {
            traceId = TraceIdUtil.generateTraceId();
        }
        TraceIdUtil.setTraceId(traceId);
        log.info("Put traceId ({}) to mdc", traceId);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String traceId = TraceIdUtil.getTraceId();
        if (StrUtil.isNotBlank(traceId)) {
            log.info("Remove traceId ({}) from mdc", traceId);
            MDC.remove(TraceLogConstants.TRACE_ID);
        }
    }
}